# -*- coding:utf-8 -*-
"""

"""
# -*- coding:utf-8 -*-
"""

"""

import requests
import re
from bs4 import BeautifulSoup
import time
from WriteData import writedata


def get_html_text(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }
    try:
        r = requests.get(url, timeout=30, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_urls(url):
    text = get_html_text(url)
    if not text:
        return None
    soup = BeautifulSoup(text, 'lxml')
    data = soup.select('.news-con h2 a')
    urls = [url['href'] for url in data]
    return urls


#
# url = 'http://www.bbcaijing.cn/article/rating/page/1'
# print(get_urls(url))


def get_datas(url):
    text = get_html_text(url)
    print('{}页面获取中'.format(url))
    if not text:
        return None
    soup = BeautifulSoup(text, 'lxml')
    title = soup.select_one('.title').get_text()
    postText = str(soup.select_one('.single-main .post-con p'))
    ctime = soup.select_one('.post-time time').get_text()
    zhaiyao = soup.select_one('.name').get_text()
    d = {"title": title, "postText": postText, "ctime": ctime, "jigou": zhaiyao}
    writedata(d)
    print(d)
    print('{}记录完成'.format(url))



#
# url = 'http://www.bbcaijing.cn/article/rating/20152.html'
# get_datas(url)


def result():
    a = 1
    while a < 3:
        url = 'http://www.bbcaijing.cn/article/rating/page/{}'
        url = url.format(a)
        urllist = get_urls(url)
        for url in urllist:
            get_datas(url)
        a += 1


#
result()

# with open('url.txt', encoding='utf-8') as f:
#     for x in f:
#         get_datas(x)
#         time.sleep(5)
